import { ITEM_TYPE, SHOW_ITEM_TYPE } from "../../config/mod_def";
import { BASE_HP, GameModel, GROW_HP } from "../../config/play_def";
import { CommonBuff } from "../../config/role_def";
import { Control_Listen, PlayGround_Listen, UI_Layer, UI_Listen } from "../../config/ui_def";
import util, { shake } from "../tool/util";
import { Sdk_Platform, OPPO_AD_CONFIG, Ad_Type } from '../../frame/constants';
module.exports = cc.Class({
    extends: cc.Component,
    properties: {
        status: false,  // 游戏战斗状态 status
        pause: false,   // 游戏暂停状态
        wait: false,    // 检测下一队列状态

        timeCount: 0,    // 下一队计时
        timeWait: 0,     // 下一队需要等待的时间

        pass_id: 0,      // 关卡id
        // 记录用参数
        gameTime: 0,     // 本次战斗信息
        gameSec: 0,      // 本次战斗秒数取整

        model: {
            type: cc.Enum(GameModel),
            default: GameModel.ClearPass
        },
        isTrail: false,
        trailID: 1001,
    },
    // 初始化
    initInfo() {
        this.damegeDict = {}        // 伤害统计数量
        this.deathDict = {}         // 击杀怪物数量
        this.damegeCount = 0        // 伤害
        this.classDict = {}         // 击杀单位类型
        this.hurtCount = 0          // 受伤统计
        this.number_of_attacks = 0  // 受攻击次数统计

        this.hpMax = this.getHpBaseMax()        // 生命值上限
        this.hp = this.hpMax

        this.status = false
        this.pause = false
        this.wait = false

        // 时间清空
        this.timeCount = 0
        this.timeWait = 0
        this.hurtNeedTime = this.randomNum(1, 4)
        this.haveShowTestSkill = false
    },
    // 增加道具
    addItem(param, num, type) {
        let info
        switch (type) {
            case SHOW_ITEM_TYPE.BY_INFO:
                info = param
                break
            case SHOW_ITEM_TYPE.BY_ID:
            default:
                info = he.db.getData("Item", param)
                break;
        }
        switch (info.type) {
            case ITEM_TYPE.COIN:
                let coin = he.local.getJson('coin', 'user')
                coin += parseInt(num)
                he.local.setJson('coin', coin, 'user')
                break;
            case ITEM_TYPE.ROLE:
                let team = he.local.getJson('team', 'user')
                team.push({
                    id: 1003,               // 角色编号
                    order: -1,              // 站位排序
                    equips: [1, 0, 0, 0],     // 装备等级
                    hand: 0,                 // 选择装备
                })
                he.local.setJson('team', team, 'user')
                break
            case ITEM_TYPE.CARD:
                let cardList = he.local.getJson('card', 'user')
                // console.log(this.itemGroup[param.index])
                cardList.push({ id: parseInt(info.icon), lv: parseInt(num) })
                he.local.setJson('card', cardList, 'user')
                break
            case ITEM_TYPE.ITEM:

            default:
                let bag = he.local.getJson("bag", 'user')
                if (info.overlay) {
                    let no_have = true
                    for (let i = 0; i < bag.length; i++) {
                        if (bag[i].id == info.id) {
                            no_have = false
                            bag[i].num += parseInt(num)
                        }
                    }
                    if (no_have) {
                        bag.push({ id: info.id, num: parseInt(num) })
                    }
                } else {
                    bag.push({ id: info.id, num: parseInt(num) })
                }
                he.local.setJson("bag", bag, 'user')
                break;
        }
    },
    // 删除道具
    delItem(param, num, type) {
        let info
        switch (type) {
            case SHOW_ITEM_TYPE.BY_INFO:
                info = param
                break
            case SHOW_ITEM_TYPE.BY_ID:
            default:
                info = he.db.getData("Item", param)
                break;
        }
        switch (info.type) {
            case ITEM_TYPE.COIN:
                let coin = he.local.getJson('coin', 'user')
                coin -= num
                if (coin < 0) {
                    coin = 0
                }
                he.local.setJson('coin', coin, 'user')
                break;
            case ITEM_TYPE.ITEM:
            default:
                let bag = he.local.getJson("bag", 'user')
                if (info.overlay) {
                    for (let i = bag.length - 1; i >= 0; i--) {
                        if (bag[i].id == info.id) {
                            bag[i].num -= num
                            if (bag[i].num <= 0) {
                                bag.splice(i, 1)
                            }
                        }
                    }
                } else {
                    for (let i = bag.length - 1; i >= 0; i--) {
                        if (bag[i].id == info.id) {
                            bag.splice(i, 1)
                        }
                    }
                }
                he.local.setJson("bag", bag, 'user')
                break;
        }
    },
    // cost 单个数值
    checkItem(cost) {
        let cost_item = cost.split('_')
        let info = he.db.getData("Item", parseInt(cost_item[0]))
        let num = parseInt(cost_item[1])

        switch (info.type) {
            case ITEM_TYPE.COIN:
                let coin = he.local.getJson('coin', 'user')
                if (coin >= num) {
                    return true
                }
                else {

                    return false
                }
                break;
            case ITEM_TYPE.ITEM:
            default:
                let bag = he.local.getJson("bag", 'user')
                if (info.overlay) {
                    for (let i = bag.length - 1; i >= 0; i--) {
                        if (bag[i].id == info.id) {
                            if (num > bag[i].num) {
                                return false
                            } else {
                                return true
                            }
                        }
                    }
                } else {
                    let count = 0
                    for (let i = bag.length - 1; i >= 0; i--) {
                        if (bag[i].id == info.id) {
                            count += 1
                        }
                    }
                    if (count >= num) {
                        return true
                    }
                }
                break;
        }
        return false
    },
    //检查金币
    checkIcon(costList, pageName) {
        // console.log(costList)
        let cost_list = costList.split("#")
        let cost_item = []
        switch (common.sdk_env) {
            case Sdk_Platform.OPPO:
                gg.uiManager.addPage(UI_Layer.Pop, {
                    name: 'getCoinPage',
                    cover: true,
                    add_coin_func: (res => {
                        he.ad.showVideo(OPPO_AD_CONFIG.videoId[1], () => {
                            for (let i = 0; i < cost_list.length; i++) {
                                let infoGrp = cost_list[i].split('_')
                                this.addItem(infoGrp[0], infoGrp[1])
                            }
                            switch (pageName) {
                                case 'merge':
                                    gg.eventManager.emit('card', { type: UI_Listen.SKILL_UPDATEMERGE })
                                    break
                                case 'equip':
                                    gg.eventManager.emit('equip', { type: UI_Listen.EQUIP_DETAILUPDATE })
                                    break
                            }
                            gg.uiManager.addPage(UI_Layer.Load, {
                                name: 'rewardPage',
                                itemGrp: cost_list,
                                cover: true,
                                close: true,
                                gameOver: true,
                            })
                        })
                    }),
                    showList: cost_list
                })
                break
            case Sdk_Platform.VIVO:
                gg.uiManager.addPage(UI_Layer.Pop, {
                    name: 'getCoinPage',
                    cover: true,
                    add_coin_func: (res => {
                        he.ad.showVideo(() => {
                            for (let i = 0; i < cost_list.length; i++) {
                                let infoGrp = cost_list[i].split('_')
                                this.addItem(infoGrp[0], infoGrp[1])
                            }
                            switch (pageName) {
                                case 'merge':
                                    gg.eventManager.emit('card', { type: UI_Listen.SKILL_UPDATEMERGE })
                                    break
                                case 'equip':
                                    gg.eventManager.emit('equip', { type: UI_Listen.EQUIP_DETAILUPDATE })
                                    break
                                default:
                                    gg.eventManager.emit('topBar', UI_Listen.TOP_UPDATE_DIAMOND)
                                    break
                            }
                        })
                    }),
                    showList: cost_list
                })
                break

            case Sdk_Platform.WECHAT:
                gg.uiManager.addPage(UI_Layer.Pop, {
                    name: 'getCoinPage',
                    cover: true,
                    add_coin_func: (res => {
                        he.ad.showVideo(() => {
                            for (let i = 0; i < cost_list.length; i++) {
                                let infoGrp = cost_list[i].split('_')
                                this.addItem(infoGrp[0], infoGrp[1])
                            }
                            switch (pageName) {
                                case 'merge':
                                    gg.eventManager.emit('card', { type: UI_Listen.SKILL_UPDATEMERGE })
                                    break
                                case 'equip':
                                    gg.eventManager.emit('equip', { type: UI_Listen.EQUIP_DETAILUPDATE })
                                    break
                            }
                        })
                    }),
                    showList: cost_list
                })
                break
            case Sdk_Platform.HUAWEI:
                gg.uiManager.addPage(UI_Layer.Pop, {
                    name: 'getCoinPage',
                    cover: true,
                    add_coin_func: (res => {
                        he.ad.showVideo(() => {
                            for (let i = 0; i < cost_list.length; i++) {
                                let infoGrp = cost_list[i].split('_')
                                this.addItem(infoGrp[0], infoGrp[1])
                            }
                            switch (pageName) {
                                case 'merge':
                                    gg.eventManager.emit('card', { type: UI_Listen.SKILL_UPDATEMERGE })
                                    break
                                case 'equip':
                                    gg.eventManager.emit('equip', { type: UI_Listen.EQUIP_DETAILUPDATE })
                                    break
                            }
                        })
                    }),
                    showList: cost_list
                })
                break
            default:
                gg.uiManager.addPage(UI_Layer.Pop, {
                    name: 'getCoinPage',
                    cover: true,
                    add_coin_func: (res => {
                        for (let i = 0; i < cost_list.length; i++) {
                            let infoGrp = cost_list[i].split('_')
                            this.addItem(infoGrp[0], infoGrp[1])
                        }
                        switch (pageName) {
                            case 'merge':
                                gg.eventManager.emit('card', { type: UI_Listen.SKILL_UPDATEMERGE })
                                break
                            case 'equip':
                                gg.eventManager.emit('equip', { type: UI_Listen.EQUIP_DETAILUPDATE })
                                break
                            default:
                                gg.eventManager.emit('topBar', UI_Listen.TOP_UPDATE_DIAMOND)
                                break
                        }
                    }),
                    showList: cost_list

                })
                break;
        }
        return false
    },
    // 检查 不能叠加的物品不适合该方法
    // cost 检查字符串
    // del 是否扣除
    checkItemStr(cost, del) {
        let cost_list = cost.split("#")
        let check_cost = true
        for (let i = 0; i < cost_list.length; i++) {
            if (!this.checkItem(cost_list[i])) {
                check_cost = false
                break
            }
        }
        if (check_cost) {
            if (del) {
                for (let i = 0; i < cost_list.length; i++) {
                    let del_item = cost_list[i].split('_')
                    this.delItem(parseInt(del_item[0]), parseInt(del_item[1]))
                }
                return true
            } else {
                return true
            }
        }
        return false
    },
    // 初始化关卡信息
    goPass(passid) {

        this.user_team = []
        let user_team = he.local.getJson('team', 'user')   // 
        let guideList = he.local.getJson('guideList', 'user')
        this.card_team = he.local.getJson('card_team', 'user')   // 
        this.initInfo()
        let passInfo
        for (let i = 0; i < user_team.length; i++) {
            if (user_team[i].order > 0) {
                this.user_team.push(user_team[i])
            }
        }
        this.gameTime = 0
        this.gameSec = 0
        let passTable
        if (!guideList[5]) {
            passInfo = he.db.getData('TryPass', 70101)

            this.model = passInfo.type      // 关卡类型
            this.pass_list = []             // 所有队列
            this.pass_index = 0             // 队列序号
            switch (this.model) {
                case GameModel.ClearPass:
                    passTable = he.db.getDataListByArgs('TryPassSort', { 'passId': 70101 })
                    passTable = passTable.sort(this.orderPass)
                    let over_wait = 0   // 时间
                    for (let i = 0; i < passTable.length; i++) {
                        if (passTable[i].teamId) {
                            let teamData = he.db.getData('PassTeam', passTable[i].teamId)
                            over_wait += teamData.teamWait
                            this.pass_list.push(teamData)
                        } else {
                            he.error("数据未填写")
                        }
                    }
                    break
            }
        }
        else {
            this.pass_id = passid
            passInfo = he.db.getData('Pass', passid)        // 关卡信息

            this.model = passInfo.type      // 关卡类型
            this.pass_list = []             // 所有队列
            this.pass_index = 0             // 队列序号
            switch (this.model) {
                case GameModel.ClearPass:
                    passTable = he.db.getDataListByArgs('PassSort', { 'passId': passid })
                    passTable = passTable.sort(this.orderPass)
                    let over_wait = 0   // 时间
                    for (let i = 0; i < passTable.length; i++) {
                        if (passTable[i].teamId) {
                            let teamData = he.db.getData('PassTeam', passTable[i].teamId)
                            over_wait += teamData.teamWait
                            this.pass_list.push(teamData)
                        } else {
                            he.error("数据未填写")
                        }
                    }
                    break
            }
        }
    },
    getRoleByRoleID(id) {
        for (let i = 0; i < this.user_team.length; i++) {
            if (this.user_team[i].id == id) {
                return this.user_team[i]
            }
        }
        return null
    },
    // 基础血量
    getHpBaseMax() {
        // 根据角色进行累加
        let maxHp = BASE_HP
        for (let i = 0; i < this.user_team.length; i++) {
            let base_lv = 0
            for (let j = 0; j < this.user_team[i].equips.length; j++) {
                if (!base_lv) {
                    base_lv = this.user_team[i].equips[j]
                }
                if (base_lv > this.user_team[i].equips[j]) {
                    base_lv = this.user_team[i].equips[j]
                }
            }
            maxHp += base_lv * GROW_HP
        }
        return maxHp
    },
    updateHpMax() {
        let maxHp = this.getHpBaseMax()
        let hpMaxBuff = gg.control.getBuff(CommonBuff.HP_MAX_UP)
        let hpMax = maxHp + hpMaxBuff
        if (this.hp == hpMax) {
            this.hp = hpMax
        } else {
            this.hp = this.hp + hpMaxBuff
        }
        gg.eventManager.emit('topInfo', PlayGround_Listen.UPDATE_HP, this.hp)
    },
    // 更新计时
    updateWait(dt) {
        if (this.status && !this.pause) {
            this.gameTime += dt // 游戏时间记录
            if (this.wait) {
                this.timeCount += dt
                if (this.timeCount >= this.timeWait) {
                    this.wait = false
                    this.timeCount = 0
                    this.timeWait = 0
                    this.joinTeam()
                }
            }
        }
    },
    // 关卡排序
    orderPass(a, b) {
        return a.index - b.index
    },
    // 下一波 
    nextWave() {
        if (this.timeWait) {
            this.wait = true
        } else {
            let waveTeam = this.pass_list[this.pass_index]
            if (!waveTeam) {
                switch (this.model) {
                    case GameModel.ClearPass:
                        gg.boidsManager.changeOver(true)
                        break
                }
                return
            }
            switch (this.model) {
                case GameModel.ClearPass:
                    if (waveTeam.teamWait) {
                        this.timeWait = waveTeam.teamWait
                        this.nextWave()
                    } else {
                        this.joinTeam()
                    }
                    break
            }
        }
    },
    // 加入队伍
    joinTeam() {
        let waveTeam = this.pass_list[this.pass_index]
        this.pass_index += 1
        // // 测试用只出一波
        // // if(this.pass_index > 0){
        // //     return
        // // }
        // // waveTeam.teamCode = "0#1#1#1#0"
        if (waveTeam.teamMenber) {
            let teamMenber = waveTeam.teamMenber.split("#")
            let teamCode = waveTeam.teamCode.split("#")
            for (let i = 0; i < teamCode.length; i++) {//这个for循环参数是什么teamCode
                if (parseInt(teamCode[i])) {
                    gg.boidsManager.addMonsterWait(i, teamMenber[teamCode[i] - 1], this.pass_index)
                }
            }
        } else {
            this.nextWave()
        }
    },
    // 检查是否拥有下一波
    checkWave() {
        if (this.pass_list[this.pass_index]) {
            return true
        }
        return false
    },
    // 杀怪计时
    // 伤害值记录
    saveDamege(key, v) {
        if (this.damegeDict[key]) {
            this.damegeDict[key] += v
        } else {
            this.damegeDict[key] = v
        }
        this.damegeCount += v
    },
    // 记录击杀数
    saveHitDeath(key, v) {
        if (this.deathDict[key]) {
            this.deathDict[key].push(v)
        } else {
            this.deathDict[key] = [v]
        }
    },
    // 记录击杀类型
    saveDeathClass(key) {
        // if (info) {
        //     let class_arr = info   //.split("#")
        //     for (let i in this.classDict) {
        //         if (this.classDict[i]==info) {
        //             this.classDict[i] += 1
        //         } else {
        //             this.classDict.push({info:1})
        //             // this.classDict[info] = 1
        //         }
        //     }
        // }
        if (this.classDict[key]) {
            this.classDict[key] += 1
        } else {
            this.classDict[key] = 1
        }
    },
    // 费血
    hurtHp(v) {
        let res = this.hp - v
        if (res <= 0) {
            shake(true)
            this.gameOver()
            this.hp = 0
        } else {
            shake()
            this.hp = res
        }
        this.hurtCount += v
        //受伤次数
        this.number_of_attacks++
        if (this.number_of_attacks >= this.hurtNeedTime && !this.haveShowTestSkill) {
            this.haveShowTestSkill = true
            // let team = he.local.getJson('team', 'user')
            // let teamGrp = []
            // for (let i = 0; i < team.length; i++) {
            //     if (team[i].order > 0) {
            //         teamGrp.push(team[i])
            //     }
            // }
            // let idGrp = { '1001': 3009, '1002': 3010, '1003': 3011, '1004': 3012, '1005': 3030 }
            // let randomId = idGrp[`${teamGrp[this.randomNum(0, teamGrp.length - 1)].id}`]
            // let info = { id: randomId, lv: 3 }
            // switch (common.sdk_env) {
            //     case Sdk_Platform.WECHAT:
            //         gg.uiManager.addPage(UI_Layer.Cover, {
            //             name: 'tryoutPage',
            //             skillInfo: info,
            //             cover: true
            //         })
            //         break
            //     case Sdk_Platform.VIVO:
            //         gg.uiManager.addPage(UI_Layer.Cover, {
            //             name: 'tryoutPage',
            //             skillInfo: info,
            //             cover: true
            //         })
            //         break
            //     default:
            //         break
            // }
        }
        gg.eventManager.emit('topInfo', PlayGround_Listen.UPDATE_HP_ANI)
        gg.control.hitAni()
    },

    //范围内的随机数
    randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },
    // 清除场景内容
    clearPlayground() {
        gg.boidsManager.clearBoids()
        gg.bulletManager.clearBullet()
        for (let key in gg.control.roleScript) {
            gg.control.roleScript[key].stopAttack()
        }
    },
    // 开始关卡
    startPass() {
        this.status = true
        gg.control.updateInfo()
        switch (this.model) {
            case GameModel.ClearPass:
                this.nextWave()
                break
        }
        he.voice.playMusic('play', 'voice')
    },
    // 游戏失败
    gameOver() {
        if (!this.status) {
            return
        }
        he.error("游戏失败")
        this.status = false
        gg.uiManager.addPage(UI_Layer.Pop, {
            name: 'GameOverPage',
            status: false,
            cover: true,
            cover_opacity: 200
        })
        gg.control.roleInit()
        gg.eventManager.emit('skill', Control_Listen.SKILL_CD_CLEAR)

        this.clearPlayground()
    },
    // 游戏胜利
    gameWin() {
        if (!this.status) {
            return
        }
        gg.uiManager.addPage(UI_Layer.Pop, {
            name: 'GameOverPage',
            status: true,
            cover: true,
            cover_opacity: 200
        })
        he.error("游戏胜利")
        this.status = false
        gg.control.roleInit()
        gg.eventManager.emit('skill', Control_Listen.SKILL_CD_CLEAR)

        this.clearPlayground()
    },
    // 游戏重启
    gameRestart() {
        this.status = false
        this.clearPlayground()
        this.goPass(this.pass_id)

        gg.eventManager.emit('topInfo', PlayGround_Listen.UPDATE_HP)
        gg.eventManager.emit('skill', Control_Listen.SKILL_CD_CLEAR)

        gg.control.updateHp()
        gg.control.roleInit()
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'StartGuide',
            cover: true,
        })
    },

    randomChaOrBanner() {
        let randonNum = util.randomNum(0, 100)
        if (randonNum >= 0 && randonNum <= 50) {
            return Ad_Type.INSERT
        } else {
            return Ad_Type.BANNER
        }
    },
});
